package com.example.seh.square.simple;



import static com.example.seh.square.simple.HttpServer.IP;
import static com.example.seh.square.simple.HttpServer.IP2;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.seh.R;
import com.example.seh.add.errands.AddErrandsActivity;
import com.example.seh.constant.Constant;
import com.example.seh.square.Post;
import com.example.seh.square.SquareAdapter;
import com.example.seh.square.custom.SampleCircleImageView;
import com.example.seh.util.BackUtil;
import com.example.seh.util.ImgUtil;
import com.example.seh.util.JudgeContent;
import com.example.seh.util.UserMsg;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jidcoo.android.widget.commentview.CommentView;
import com.jidcoo.android.widget.commentview.callback.OnCommentLoadMoreCallback;
import com.jidcoo.android.widget.commentview.callback.OnItemClickCallback;
import com.jidcoo.android.widget.commentview.callback.OnPullRefreshCallback;
import com.jidcoo.android.widget.commentview.callback.OnReplyLoadMoreCallback;
import com.jidcoo.android.widget.commentview.callback.OnScrollCallback;
import com.jidcoo.android.widget.commentview.defaults.DefaultCommentModel;
import com.jidcoo.android.widget.commentview.defaults.DefaultViewStyleConfigurator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * 对于CommentView的默认数据模型的简单使用（使用服务端）
 * 使用默认样式配置器，默认数据模型，默认布局
 */

public class DefaultUseWithServerActivity extends AppCompatActivity {
    private CommentView commentView;
    private String data;
    private Gson gson;
    private EditText user, editor;
    private Button button;
    private CircleImageView imageLogo;
    private ImageView pic1,pic2,pic3;
    private TextView editorName,editorTime,editTitle,editContent;

    private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");

    private boolean isReply = false;
    private boolean isChildReply = false;
    private int cp, rp;
    private long fid, pid;
    private int postId;
    private DefaultCommentModel.Comment.Reply reply;
    /**
     * 数据处理
     */
    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            data = (String) msg.obj;
            switch (msg.what) {
                case 1:
                    if (data == null) {
                        commentView.loadFailed(true);
                        return;
                    }
                    commentView.loadComplete(gson.fromJson(data, DefaultCommentModel.class));
                    break;
                case 2:
                    if (data == null) {
                        commentView.refreshFailed("请求数据失败，刷新失败", true);
                        return;
                    }
                    commentView.refreshComplete(gson.fromJson(data, DefaultCommentModel.class));
                    break;
                case 3:
                    if (data == null) {
                        commentView.loadMoreFailed("请求数据失败，加载更多失败", false);
                        return;
                    }
                    commentView.loadMoreComplete(gson.fromJson(data, DefaultCommentModel.class));
                    break;
                case 4:
                    if (data == null) {
                        commentView.loadMoreReplyFailed("请求数据失败，加载更多回复失败", false);
                        return;
                    }
                    commentView.loadMoreReplyComplete(gson.fromJson(data, DefaultCommentModel.class));
                    break;
                case 5:
                    commentView.addReply(reply, cp);
                    load(IP + "findAllComment?postId="+postId+"&currentPage=1", 2);
                    break;
                case 6:
                    load(IP + "findAllComment?postId="+postId+"&currentPage=1", 2);
                    break;
            }
        }
    };

    /**
     * 网络请求
     *
     * @param url
     * @param code
     */
    private void load(String url, int code) {
        HttpServer.getData(url, myHandler, code);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_use);

        gson = new Gson();
        user = findViewById(R.id.user);
        editor = findViewById(R.id.editor);
        button = findViewById(R.id.button);
        imageLogo = (CircleImageView) findViewById(R.id.detail_page_userLogo);
        pic1 = findViewById(R.id.detail_pic1);
        pic2 = findViewById(R.id.detail_pic2);
        pic3 = findViewById(R.id.detail_pic3);
        editorName = findViewById(R.id.detail_page_userName);
        editorTime = findViewById(R.id.detail_page_time);
        editTitle = findViewById(R.id.detail_page_title);
        editContent = findViewById(R.id.detail_page_story);

        Intent intent = getIntent();
        if (intent!=null){
            postId = (intent.getIntExtra("postId",-1));

        }

        getContentData();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userStr = UserMsg.userDTO.getUsername();
                String content = editor.getText().toString();



                if (!content.isEmpty()) {
                    JudgeContent.setData(content, new JudgeContent.DataCallback() {
                        @Override
                        public void onFailure() {
                            Log.e("fail","发送失败");
                        }

                        @Override
                        public void onResponse(String data) {
                            try {
                                JSONObject jsonObject = new JSONObject(data);
                                JSONArray wordList = jsonObject.getJSONArray("word_list");
//                                String encodedUsername = URLEncoder.encode(userStr, StandardCharsets.UTF_8.toString());
//                                String encodedContent = URLEncoder.encode(data, StandardCharsets.UTF_8.toString());

                                if (wordList.length() == 0) {

                                    if (isReply && isChildReply) {
                                        //现在需要构建一个回复数据实体类
                                        reply = new DefaultCommentModel.Comment.Reply();
                                        reply.setKid(fid);
                                        reply.setReplierName(userStr);
                                        reply.setReply(content);
                                        reply.setDate(System.currentTimeMillis());
                                        reply.setPid(pid);
                                        load(IP2 + "kid=" + fid + "&replyName=" + userStr + "&replyContent=" + content + "&pid=" + pid +"&userId="+ UserMsg.userDTO.getUserId(), 5);
                                    } else if (isReply && !isChildReply) {
                                        //现在需要构建一个回复数据实体类
                                        reply = new DefaultCommentModel.Comment.Reply();
                                        reply.setKid(fid);
                                        reply.setReplierName(userStr);
                                        reply.setReply(content);
                                        reply.setDate(System.currentTimeMillis());
                                        reply.setPid(0);
                                        load(IP2 + "kid=" + fid + "&replyName=" + userStr + "&replyContent=" + content + "&pid=0" + "&userId="+ UserMsg.userDTO.getUserId(), 5);
                                    } else {
                                        load(IP + "insertCommentAboutPost?postId="+postId+"&username=" + userStr + "&content=" + content+"&userId=" + UserMsg.userDTO.getUserId(), 6);
                                    }
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            editor.setText("");
                                        }
                                    });

                                    //隐藏软键盘
                                    InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

                                } else {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(DefaultUseWithServerActivity.this,"发布内容包含敏感词汇，请修改后发布",Toast.LENGTH_LONG).show();
                                        }
                                    });
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });


                } else {
                    Toast.makeText(DefaultUseWithServerActivity.this, "内容都不能为空", Toast.LENGTH_LONG).show();
                }
            }
        });
        commentView = findViewById(R.id.myCommentView);//初始化控件
        commentView.setViewStyleConfigurator(new DefaultViewStyleConfigurator(this));
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        TextView tv1 = new TextView(this);
        tv1.setText("没有评论哦，快去抢沙发吧~");
        tv1.setGravity(Gravity.CENTER);
        TextView tv2 = new TextView(this);
        tv2.setText("网络出现异常，无法获取数据。\n如果需要服务端程序进行测试，请联系我：18875116461");
        tv2.setGravity(Gravity.CENTER);
        tv1.setLayoutParams(lp);
        tv2.setLayoutParams(lp);
        //设置空数据视图
        commentView.setEmptyView(tv1);
        //设置错误视图
        commentView.setErrorView(tv2);
        //获取callbackBuilder添加事件回调
        commentView.callbackBuilder()
                .setOnPullRefreshCallback(new MyOnPullRefreshCallback())
                .setOnCommentLoadMoreCallback(new MyOnCommentLoadMoreCallback())
                .setOnReplyLoadMoreCallback(new MyOnReplyLoadMoreCallback())
                .setOnItemClickCallback(new MyOnItemClickCallback())
                .setOnScrollCallback(new MyOnScrollCallback())
                //设置完成后必须调用CallbackBuilder的buildCallback()方法，否则设置的回调无效
                .buildCallback();
        load(IP+"findAllComment?postId="+postId+"&currentPage=1", 1);
    }

    private void getContentData() {
        OkHttpClient okHttpClient = new OkHttpClient();

        Request request = new Request.Builder()
                .get()
                .url(Constant.DETAIL_POST + postId)
                .build();
        Log.e("地址：",request.url().toString());
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp", "获取数据失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String squareData = response.body().string();
                Log.e("数据：",squareData);
                getDataFromJsonData(squareData);
            }

        });

    }

    private void getDataFromJsonData(String studyData) {
        try {
            JSONObject jsonObject = new JSONObject(studyData);
            String PlanDataStr = jsonObject.getString("data");
            Gson gson = new Gson();
            Type type = new TypeToken<Post>(){}.getType();
            Post post = gson.fromJson(PlanDataStr,type);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if (post.getUserDTO().getPic()!=null){
                                    if (!"".equals(post.getUserDTO().getPic())) {
                                        Glide.with(getApplicationContext()).load(post.getUserDTO().getPic()).diskCacheStrategy(DiskCacheStrategy.NONE).into(imageLogo);
                                    }
                            }
                        }
                    }).start();

                    editorName.setText(post.getUserDTO().getUsername());
                    try {
                        editorTime.setText(SquareAdapter.getTime(dateFormat.parse(post.getCreateTime()).getTime()));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    editTitle.setText(post.getTitle());
                    editContent.setText(post.getContent());

                    if (post.getPicPath()!=null){
                        String[] paths = post.getPicPath().split(";");
                        if (!paths[0].isEmpty()){

                            Glide.with(getApplicationContext())
                                    .load(paths[0])
                                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                                    .into(pic1);
                        }
                        if (paths.length>=2 && !paths[1].isEmpty()){

                            Glide.with(getApplicationContext())
                                    .load(paths[1])
                                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                                    .into(pic2);
                        }
                        if (paths.length>=3 && !paths[2].isEmpty()){

                            Glide.with(getApplicationContext())
                                    .load(paths[2])
                                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                                    .into(pic3);
                        }
                    }else {
                        pic1.setVisibility(View.GONE);
                        pic2.setVisibility(View.GONE);
                        pic3.setVisibility(View.GONE);
                    }
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Message message = new Message();
        message.what = 7;
        myHandler.sendMessage(message);
    }

    /**
     * 下拉刷新回调类
     */
    class MyOnPullRefreshCallback implements OnPullRefreshCallback {

        @Override
        public void refreshing() {
            load(IP+"findAllComment?postId="+postId+"&currentPage=1", 2);
            //load(IP + "/api?do=gc", 2);
        }

        @Override
        public void complete() {
            //加载完成后的操作
        }

        @Override
        public void failure(String msg) {
            if (msg != null)
                Toast.makeText(DefaultUseWithServerActivity.this, msg, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 上拉加载更多回调类
     */
    class MyOnCommentLoadMoreCallback implements OnCommentLoadMoreCallback {

        @Override
        public void loading(int currentPage, int willLoadPage, boolean isLoadedAllPages) {
            if (!isLoadedAllPages) {
                load(IP + "findAllComment?postId="+postId+"&currentPage=" + willLoadPage, 3);
            }
        }

        @Override
        public void complete() {
            //加载完成后的操作
        }

        @Override
        public void failure(String msg) {
            if (msg != null)
                Toast.makeText(DefaultUseWithServerActivity.this, msg, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 回复加载更多回调类
     */
    class MyOnReplyLoadMoreCallback implements OnReplyLoadMoreCallback<DefaultCommentModel.Comment.Reply> {

        @Override
        public void loading(DefaultCommentModel.Comment.Reply reply, int willLoadPage) {
            //在默认回复数据模型中，kid作为父级索引
            //为了扩展性，把对应的具体模型传了出来，可根据具体需求具体使用
            load(IP + "findCommentById?" + "id=" + reply.getKid() + "&currentPage=" + willLoadPage, 4);
        }

        @Override
        public void complete() {
            //加载完成后的操作
        }

        @Override
        public void failure(String msg) {
            if (msg != null)
                Toast.makeText(DefaultUseWithServerActivity.this, msg, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 点击事件回调
     */
    class MyOnItemClickCallback implements OnItemClickCallback<DefaultCommentModel.Comment, DefaultCommentModel.Comment.Reply> {

        @Override
        public void commentItemOnClick(int position, DefaultCommentModel.Comment comment, View view) {
            isReply = true;
            cp = position;
            isChildReply = false;
            fid = comment.getFid();
            editor.setHint("回复@" + comment.getPosterName() + ":");
        }

        @Override
        public void replyItemOnClick(int c_position, int r_position, DefaultCommentModel.Comment.Reply reply, View view) {
            isReply = true;
            cp = c_position;
            rp = r_position;
            isChildReply = true;
            fid = reply.getKid();
            pid = reply.getId();
            editor.setHint("回复@" + reply.getReplierName() + ":");
        }
    }

    class MyOnScrollCallback implements OnScrollCallback {

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            isReply = false;
            if (editor.getText().toString().length()>0){
                editor.setText("");
            }
            editor.setHint("发表你的评论吧~");
        }

        @Override
        public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

        }
    }

}
